package com.example.demo.controller;


import com.example.demo.dao.DepartmentDao;
import com.example.demo.dao.EmployeeDao;
import com.example.demo.pojo.Department;
import com.example.demo.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

@Controller
public class EmployeeController {
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String list(Model model) {
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps", employees);
        return "emps/list";
    }


    //增加员工
    @GetMapping("/emp")
    public String toAddPage(Model model) {
        //查出所有部门信息
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments", departments);
        return "emps/addEmp";
    }

    //保存员工信息
    @PostMapping("/emp")
    public String saveEmp(Employee employee) {
        employeeDao.save(employee);//调用底层 保存信息
        return "redirect:/emps";//重定向不需要传递数据，是用来加载信息的
    }


    //修改员工信息
    @GetMapping("/emp/{id}") //牢记这种表达方式
    public String toUpdate(@PathVariable("id") Integer id, Model model) {
        //查询当前员工信息
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("emp", employee);
        //查询所有部门信息（因为需要修改部门名称）
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments", departments);
        return "emps/update";
    }

    //保存员工信息
    @PostMapping("/updateSave")
    public String updateSave(Employee employee) { //疑问？为啥他知道前端给他送过来了一个employee.是应为是method=post？吗
        employeeDao.save(employee);//调用底层 保存信息
        return "redirect:/emps";//重定向不需要传递数据，是用来加载信息的
    }


    //删除员工
    @RequestMapping("/deleteEmp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
